package com.ynunicom.midplatform.sys.login;

import com.ynunicom.midplatform.common.result.ResponseEntity;
import com.ynunicom.midplatform.common.util.Md5Util;
import com.ynunicom.midplatform.sys.user.SysUser;
import com.ynunicom.midplatform.sys.user.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录Controller
 *
 * @author duwei
 */
@RestController
public class LoginController {

    @Autowired
    private SysUserService userInfoService;

    @PostMapping("/login")
    @ResponseBody
    public ResponseEntity login(String loginName, String password) {
        //查询数据库对比
        SysUser sysUser = userInfoService.findByLoginName(loginName);
        if (sysUser != null) {
            //加密
            String psd = Md5Util.MD5Encode(password, "utf-8", false);
            if (sysUser.getPassword().equals(psd)) {
                // 1、获取Subject实例对象
                Subject currentUser = SecurityUtils.getSubject();
                //currentUser.getSession().setTimeout(-1001l);

                // 2、判断当前用户是否登录
                if (!currentUser.isAuthenticated()) {
                    currentUser.logout();
                }

                // 3、将用户名和密码封装到UsernamePasswordToken
                UsernamePasswordToken token = new UsernamePasswordToken(loginName, psd);

                // 4、认证
                try {
                    // 传到MyAuthorizingRealm类中的方法进行认证
                    currentUser.login(token);
                    Session session = currentUser.getSession();
                    session.setAttribute("loginName", loginName);
                    session.setTimeout(-1L);
                } catch (AuthenticationException e) {
                    e.printStackTrace();
                }
                return ResponseEntity.success("登录成功");
            } else {
                return ResponseEntity.failed("登录失败，用户密码错误！");
            }
        } else {
            return ResponseEntity.failed("登录失败，用户不存在！");
        }
    }
}
